var events = require('events').EventEmitter;
var fs = require('fs');
var https = require('https');
var bingProperties = require('./bingProperties');
var t = require('./tools.js');
var $ = require('jquery');
var ET = bingProperties.ET;
var ReportRequest = function() {};
ReportRequest.prototype = Object.create(events.prototype, {
    constructor: {
        value: function() {
            events.call(this);
        },
        enumerable: false
    }
});

ReportRequest.prototype.init = function(actionName) {
    var path = bingProperties.soapXMLPath;
    this.root = ET.XML(fs.readFileSync(path + actionName + '.xml').toString());
}
ReportRequest.prototype.toXMLString = function() {
    function toXMLString() {
        return ET.tostring(this, {
            xml_declaration: false
        });
    }
    return toXMLString.call(this.root);
};
ReportRequest.prototype.send = function(wsdl) {
    //'https://adcenterapi.microsoft.com/Api/Advertiser/v8/CampaignManagement/BulkService.svc?wsdl';
    var self = this;
    var arr = wsdl.split('://');
    var pathArr = arr[1].split('/');
    var host = pathArr[0];
    pathArr.shift();
    var path = '/' + pathArr.join('/') + '/';
    var soapAction = $.trim(this.root.find('.//Action').text);
    var soapStr = this.toXMLString()
    var option = {
        host: host,
        method: 'POST',
        path: path,
        headers: {
            'Content-type': 'text/xml; charset="utf-8"',
            'Content-length': soapStr.length,
            SOAPAction: soapAction
        }
    }
    var strData = '';
    var req = https.request(option, function(res) {

        // console.log()
    })
    req.write(soapStr);
    req.end();
    req.on('response', function(res) {
        t.logTime('report on response ' + 'statusCode=[' + res.statusCode + ']');
        switch(res.statusCode) {
        case 500:
            res.on('data', function(chunk) {
                t.logTime('serverErrorData');
                strData += chunk.toString();
                // console.log(chunk.toString());
                self.emit('serverErrorData', chunk);
            });
            res.on('end', function() {
                t.logTime('serverErrorEnd');
                self.emit('serverErrorEnd', strData);
            });
            // console.log(response);
            break;
        case 200:
            self.emit('response', res);
            res.on('data', function(chunk) {
                t.logTime('report on data');
                strData += chunk.toString();
                // console.log(chunk.toString());
                self.emit('data', chunk);
            });
            res.on('end', function() {
                t.logTime('report on end');
                self.emit('end', strData);
            });
            res.on('close', function() {
                t.logTime('report on close');
                self.emit('close');
            });
            break;
        }



    });
    req.on('socket', function(socket) {
        t.logTime('report on socket');
        self.emit('socket', socket);
    });
    req.on('connect', function(response, socket, head) {
        t.logTime('report on connect');
        self.emit('connect', response, socket, head);
    });
    req.on('upgrade', function(response, socket, head) {
        t.logTime('report on upgrade');
        self.emit('upgrade', response, socket, head);
    });
    req.on('continue', function() {
        t.logTime('report on continue');
        self.emit('continue');
    });
    req.on('error', function(e) {
        t.logTime('report on error');
        self.emit('error', e);
    });

};
ReportRequest.prototype.downLoadFiled = function(url, path) {
    var self = this;
    https.get(url, function(res) {
        var fileNameReg = /\w+\.zip/;
        // console.log("<><><><><><><><><><><><><><><><><>", res.headers['content-disposition']);
        var fileName = res.headers['content-disposition'].split('"')[1];
        var downloadStream = fs.createWriteStream(path + fileName);
        res.pipe(downloadStream);
        t.logTime('report data ready');
        self.emit('reportDataReady', url);
        downloadStream.on('close', function() {
            t.logTime('report data complete');
            self.emit('reportDataComplete', path + fileName);
        })
        // console.log(fileName);
    });
}
exports.ReportRequest = ReportRequest;